package com.example.demo.controller;

import com.example.demo.entity.BankAccountEntity;
import com.example.demo.entity.dto.TransferDTO;
import com.example.demo.service.BankAccountService;
import com.example.demo.util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xzy
 * @date 2020-11-08 14:56
 * 说明：
 */
@RestController
@RequestMapping("bank_account/")
public class BankAccountController {
    private final BankAccountService bankAccountService;

    @Autowired
    public BankAccountController(@Qualifier("bankAccountServiceImpl") BankAccountService bankAccountService) {
        this.bankAccountService = bankAccountService;
    }

    /**
     * 新增一条银行账户数据
     *
     * @param newBankAccountRecord - 新增的银行账户数据
     * @return - 实际保存到数据库中的数据
     */
    @PostMapping("save")
    public Message save(@RequestBody BankAccountEntity newBankAccountRecord) {
        try {
            bankAccountService.save(newBankAccountRecord);
        } catch (IllegalArgumentException i) {
            return Message.fail("新增银行账户失败！" + i.getMessage());
        } catch (Exception e) {
            return Message.fail("新增银行账户失败！");
        }
        return Message.ok("新增银行账户成功！");
    }

    /**
     * 转账
     *
     * @param transferData - 原始账户、目标账户、转账金额
     * @return - 操作接口
     */
    @PostMapping("transfer")
    public Message transfer(@RequestBody TransferDTO transferData) {
        return bankAccountService.transfer(transferData.getFrom(), transferData.getTo(), transferData.getMoney());
    }
}
